package HUMAN;

import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.WindowConstants;

import TOOLS.SQLtool;
import TOOLS.errCodeManagement;
import TOOLS.messageTool;
import TOOLS.ImageUpload.c_ImgUpload;
import VIEWS.v_getText;
import VIEWS.v_tableInDialog;
import WORKPLACE.workPlace;


public class skillMatrixViewer4MFT {

	SQLtool sql;
	v_skillMatrixViewer p;
//	JDialog jf;
	messageTool mt = new messageTool();
	static int keyCount = 0;
	double maxOnlineLimit=c_human.maxOnlineLimit;
	c_human cHuman=null;
//	String goldenDepartment=null;
	String permission=null;
	String posisions=null;
	
	public skillMatrixViewer4MFT(SQLtool iSql,c_human iHuman,String iPermission) throws Exception {
		permission=iPermission;
		cHuman=iHuman;
		sql = iSql;
		init();
		if(workPlace.img_skill_lv1==null) {
			c_ImgUpload ciu=new c_ImgUpload(sql);
			workPlace.img_skill_lv1=new ImageIcon(ciu.getDBimage("skill_lv1"));
			workPlace.img_skill_lv2=new ImageIcon(ciu.getDBimage("skill_lv2"));
			workPlace.img_skill_lv3=new ImageIcon(ciu.getDBimage("skill_lv3"));
			workPlace.img_skill_lv4=new ImageIcon(ciu.getDBimage("skill_lv4"));
			ciu.close();
		}
	}
	
	public void init() throws Exception {
		getPosisions();
		freshEmployeeList();
		if(posisions!=null) {
			// 每个技能都要刷新每个人的技能状态
			new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						freshSkillPermission();
						String [] skillName=posisions.split(",");
						for(int i=0;i<skillName.length;i++) {
							int ii=i;
							new Thread(new Runnable() {
								@Override
								public void run() {
									try {
										freshSkillPermission_matrix(skillName[ii]);
									} catch (Exception e) {
										String str = errCodeManagement.getErrText(e.getMessage());
										if(str.contains("已被选作死锁牺牲品")) {
											;
										}else {
											mt.show(str);
										}
									}
								}
							},"freshSkillPermission_"+skillName[ii]).start();
						}
					} catch (Exception e) {
						String str = errCodeManagement.getErrText(e.getMessage());
						if(str.contains("已被选作死锁牺牲品")) {
							;
						}else {
							mt.show(str);
						}
					}
				}
			},"freshSkillPermission_all").start();
			
		}
	}

	private void freshSkillPermission() throws Exception {//positionState
		String strSql="update ps set ps.state=vtv.permissionState \r\n" + 
				"from [human].[positionState] ps \r\n" + 
				"LEFT JOIN [human].[vTrainingValidity] vtv ON vtv.number=ps.employeeID and vtv.trainingPositionIndex=ps.trainingPositionIndex \r\n" + 
				"where vtv.counter>=vtv.target and vtv.invalidTime>getdate() ";
		sql.Command(strSql);
	}
	
	private void freshSkillPermission_matrix(String skillName) throws Exception {// 按顺序刷新各级别许可证
//		freshSkillPermission_invalid_matrix(skillName);//杨部长说失效的不用在矩阵图体现
		freshSkillPermission_1234_matrix(skillName);
	}


	private void freshSkillPermission_1234_matrix(String skillName) throws Exception {
		String strSql="update pts set pts.state=null\r\n" + 
				"FROM [human].[vTrainingState] vts \r\n" + 
				"LEFT JOIN human.positionState pts ON pts.trainingPositionIndex=vts.trainingPositionIndex and pts.employeeID=vts.number\r\n" + 
				"where (vts.permissionState is null and pts.state is not null) or (vts.hopping=1) ";
		sql.Command(strSql);// 缺课程的岗位，清空等级 
		strSql="update smm set smm."+skillName+"=vtv.LV \r\n" + 
				"FROM [human].[skillMatrix_mft] smm \r\n" + 
				"LEFT JOIN [human].[vTrainingValidity] vtv ON vtv.number=smm.number and vtv.positionName='"+skillName.substring(1, skillName.length()-1)+"' \r\n" + 
				"where (smm."+skillName+"!=vtv.LV or smm."+skillName+" is null or (vtv.LV is null and smm."+skillName+" is not null) ) ";
		sql.Command(strSql);
	}

//	private void freshSkillPermission_invalid_matrix(String skillName) throws Exception {
//		String strSql="update smm set smm."+skillName+"='-1'\r\n" + 
//				"FROM [human].[skillMatrix_mft] smm \r\n" + 
//				"LEFT JOIN [human].[vTrainingValidity] vtv ON vtv.number=smm.number and vtv.positionName='"
//				+skillName+"' \r\n" + 
//				"where vtv.invalidTime<=getdate() ";
//		sql.Command(strSql);
//	}

	private void freshEmployeeList() throws Exception {
		String str="delete from [human].[skillMatrix_mft] where number in (select number from [human].[employeeList] where leaveDate<=getDate() ) ";
		sql.Command(str);
		
		str="insert [human].[skillMatrix_mft] (number) (select el.number from [human].[employeeList] el "
				+ "left join [human].[skillMatrix_mft] smm ON smm.number=el.number "
				+ "where (el.department='生产部') and len(el.number)>0 and "
//				+ "where (el.department='生产部' or el.department='工程部') and len(el.number)>0 and "
				+ "(el.leaveDate is null or el.leaveDate>getdate()) and smm.skillMatrixMFTindex is null )";
		sql.Command(str);
	}

	public void getPosisions() throws Exception {
		sql.Command("delete from [human].[skillList_mft] \r\n" + 
				"where trainingPositionIndex not in \r\n" + 
				"(select trainingPositionIndex from [human].[trainingPosition]) ");
		JTable t=sql.select("select tp.name from [human].[skillList_mft] sl \r\n" + 
				"LEFT JOIN [human].[trainingPosition] tp ON tp.trainingPositionIndex=sl.trainingPositionIndex");
		if(t!=null && t.getRowCount()>0) {
			posisions="";
			for(int i=0;i<t.getRowCount();i++) {
				posisions=posisions+"["+t.getValueAt(i, 0)+"],";
			}
		}else {
			posisions=null;
		}
	}
	
	public void close() {
		cHuman.close();
		try {
			sql.close();
		} catch (Exception e) {
			;
		}
	}
	

	public void search() {
		if (p.buttonSearch.isEnabled()) {
			try {
				String sqlStr = "select ROW_NUMBER() over (order by el.department,el.class,smm.number ) as 序号,smm.number as 工号,el.name as 姓名,el.class as 班别 \r\n" + 
						"from [human].[skillMatrix_mft] smm \r\n" + 
						"LEFT JOIN [human].[employeeList] el ON el.number=smm.number \r\n" + 
						"where el.leaveDate is null and (el.department='生产部') ";
//						"where el.leaveDate is null and (el.department='生产部' or el.department='工程部') ";
				if(posisions!=null) {
					sqlStr = "select ROW_NUMBER() over (order by el.department,el.class,smm.number ) as 序号,smm.number as 工号,el.name as 姓名,el.class as 班别, \r\n" + 
							posisions.substring(0, posisions.length()-1)+
							" from [human].[skillMatrix_mft] smm \r\n" + 
							"LEFT JOIN [human].[employeeList] el ON el.number=smm.number \r\n" + 
							"where el.leaveDate is null and (el.department='生产部') ";
//							"where el.leaveDate is null and (el.department='生产部' or el.department='工程部') ";
				}
				keyCount = 2;
				sqlStr = SQLselectAddKeyWords(sqlStr, "smm.number", p.fields[0].getText());
				sqlStr = SQLselectAddKeyWords(sqlStr, "el.name", p.fields[1].getText());
				sqlStr = SQLselectAddKeyWords(sqlStr, "el.class", p.fields[2].getText());
				
				sqlStr = sqlStr + " order by el.department,el.class,smm.number ";
				JTable t = sql.select(sqlStr);
				p.setTable(t);
//				p.tab01.updateUI();
			} catch (Exception e) {
				String str = errCodeManagement.getErrText(e.getMessage());
				mt.show(str);
			}
		}

	}
	
	

	public static String SQLselectAddKeyWords(String SQLstr, String colName, String keyWords) {
		if (keyWords.length() > 0) {
			if (keyCount == 0) {
				SQLstr = SQLstr + "where ";
			} else {
				SQLstr = SQLstr + "and ";
			}
			keyCount += 1;
			SQLstr = SQLstr + colName + " like '%" + keyWords + "%' ";
		}
		return SQLstr;
	}

	public void show() {
		this.show(null,null);
	}
	
	public void show(String iNumber) {
		show(null,iNumber);
	}

	public void show(JPanel jf) {
		show(jf,null);
	}
	
	public void show(JPanel jf,String iNumber) {
		JDialog jdd=null;
		p = new v_skillMatrixViewer();
		if(jf!=null) {
			p.iWIDTH=jf.getWidth();
			p.iHEIGHT=jf.getHeight();
		}else {
			int sw=Toolkit.getDefaultToolkit().getScreenSize().width;
			int sh=Toolkit.getDefaultToolkit().getScreenSize().height;
			p.WIDTH=(int) (0.8*sw);
			p.HEIGHT=(int) (0.8*sh);
		}
		p.myRepaint1();
		if(jf==null) {
			jdd=new JDialog();
			jdd.setSize(p.getWidth() + 20, p.getHeight() + 20);
			jdd.setLocationRelativeTo(null);
			jdd.setLayout(null);
			jdd.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
			jdd.setResizable(false);
		}else {
			jf.setLayout(null);
		}
		
		
		p.buttonSearch.addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent e) {
				search();
			}
		});

		p.buttonAdd.setText("岗位维护");
		p.buttonAdd.setVisible(true);
		p.buttonAdd.setEnabled(true);
		p.buttonAdd.addMouseListener(new MouseAdapter() {//技能维护
			public void mousePressed(MouseEvent e) {
				try {
					boolean b=cHuman.checkPermission_unReplay(permission+"_skillMatrix");
					if(b) {// 弹窗，从trainingPosition和skillList_mft中获取信息
						skillMatrixSorter sms=new skillMatrixSorter(sql);
						sms.init();
						init();
						search();
					}else {
						mt.show("授权失败");
					}
				} catch (Exception e1) {
					String str=errCodeManagement.getErrText(e1.getMessage());
					mt.show(str);
				}
			}
		});

		p.buttonDelete.setText("<html>个人<BR>技能清单</html>");
		p.buttonDelete.setVisible(true);
		p.buttonDelete.setEnabled(true);
		p.buttonDelete.addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent e) {
				try {
					int r=p.tab01.getSelectedRow();
					if(r>=0) {//	◔	◑	◕	●	
						String iNumber=""+p.tab01.getValueAt(r, 1);//工号
						String iName=""+p.tab01.getValueAt(r, 2);//姓名
						String iClass=""+p.tab01.getValueAt(r, 3);//姓名
						String strsql="delete from [human].[trainingPositionSons] \r\n" + 
								"where trainingPositionIndex not in (select trainingPositionIndex from [human].trainingPosition)";
						sql.Command(strsql);
						showSkillList(iNumber,iName,iClass);// 弹窗显示个人技能清单的类
					}else {
						mt.show("未选中员工");
					}
				} catch (Exception e1) {
					String str=errCodeManagement.getErrText(e1.getMessage());
					mt.show(str);
				}
			}
		});
		
		p.buttonEdit.setText("<html>岗位<BR>人数统计</html>");
		p.buttonEdit.setVisible(true);
		p.buttonEdit.setEnabled(true);
		p.buttonEdit.addMouseListener(new MouseAdapter() {//岗位人数统计
			public void mousePressed(MouseEvent e) {
				String strsql="select name as 岗位,[1] as 等级1,[2] as 等级2,[3] as 等级3,[4] as 等级4 from (\r\n" + 
						"	select el.number,tp.name,AAA.permissionState \r\n" + 
						"	from human.vTrainingPositionPermission AAA \r\n" + 
						"	LEFT JOIN [human].[employeeList] el ON el.number=AAA.employeeID \r\n" + 
						"	LEFT JOIN [human].[trainingPosition] tp ON tp.trainingPositionIndex=AAA.positionID \r\n" + 
						"	LEFT JOIN [human].[skillList_mft] sklm ON sklm.trainingPositionIndex=tp.trainingPositionIndex \r\n" + 
						"	where el.number is not null and el.leaveDate is null and tp.state=1 \r\n" + 
						"	and AAA.invalidTime>getdate() \r\n" + 
						"	and sklm.trainingPositionIndex is not null\r\n" + 
						") BBB \r\n" + 
						"PIVOT (\r\n" + 
						"	count(BBB.number)\r\n" + 
						"	for BBB.permissionState in ([1],[2],[3],[4])\r\n" + 
						") as CCC\r\n" + 
						"ORDER BY name  ";
				try {
					JTable t=sql.select(strsql);
					Font font=new Font("",1,(int)(p.rim*4));
					t.getTableHeader().setFont(font);
					t.setRowHeight(font.getSize()+4);
					t.setFont(font);
					new v_tableInDialog(t,p.WIDTH,p.HEIGHT,"岗位人数统计");
				} catch (Exception e1) {
					String str=errCodeManagement.getErrText(e1.getMessage());
					mt.show(str);
				}
			}
		});
		
		p.buttonView.setText("删除");
		p.buttonView.setVisible(false);
		p.buttonView.setEnabled(false);
		p.buttonView.addMouseListener(new MouseAdapter() {//删除
			public void mousePressed(MouseEvent e) {
				try {
					int r=p.tab01.getSelectedRow();
					if(r>=0) {
						boolean b=cHuman.checkPermission_unReplay(permission+"_audit");
						if(b) {
							String iState = ""+p.tab01.getValueAt(r, 1);
							if(!iState.equals("申请中")) {
								mt.show("只能删除申请中的加班安排");
								return;
							}
							String iNumber = ""+p.tab01.getValueAt(r, 2);
							String iName = ""+p.tab01.getValueAt(r, 3);
							String iTime = ""+p.tab01.getValueAt(r, 5);
							String iid = ""+p.tab01.getValueAt(r, 12);
							
							b=mt.confirm("是否删除"+iNumber+iName+"加班安排("+iTime+")？", "注意");
							if(b) {// 删除加班安排
								String sqlstr=null;
								sqlstr="update sir set sir.state=1,sir.tips=null,sir.signInAt=null,sir.signOutAt=null,sir.workTime=null,sir.overTime=null \r\n" + 
										"from [human].[signInReport] sir \r\n" + 
										"LEFT JOIN [human].[vSignInReport_type1] sir_t1 ON sir_t1.signInReportIndex=sir.signInReportIndex \r\n" + 
										"where sir.number='"+iNumber+"' and sir_t1.classAt like '"+iTime+"%' \r\n";
								sql.Command(sqlstr);
								Thread iTH1 = new Thread(new Runnable() {
									@Override
									public void run() {
										try {
											//
										} catch (Exception e) {
											String str = errCodeManagement.getErrText(e.getMessage());
											mt.show(str);
										}
									}
								});
								iTH1.start();
								sql.Command("delete from [human].[preClassOverTime] "
										+ "where preClassOverTimeIndex="+iid);
								search();
								mt.show("加班安排已删除");
							}
						}else {
							mt.show("授权失败");
						}
					}else {
						mt.show("未选中员工");
					}
				} catch (Exception e1) {
					String str=errCodeManagement.getErrText(e1.getMessage());
					mt.show(str);
				}
			}
		});
		
		p.buttonSave.setText("绩效月视图");
		p.buttonSave.setEnabled(false);
		p.buttonSave.setVisible(false);
		p.buttonSave.addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent e) {//绩效月视图
				
			}
		});
		
		p.buttonCancel.setText("加班月视图");
		p.buttonCancel.setVisible(false);
		p.buttonCancel.setEnabled(false);
		p.buttonCancel.addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent e) {//加班月视图 
				
			}
		});
		

		p.fields[0].addKeyListener(new KeyAdapter() {
			public void keyPressed(KeyEvent e) {
				if (e.getKeyChar() == KeyEvent.VK_ENTER) // 按回车键执行相应操作;
				{
					search();
					p.fields[0].requestFocus();
					p.fields[0].selectAll();
				}
			}
		});
		p.fields[1].addKeyListener(new KeyAdapter() {
			public void keyPressed(KeyEvent e) {
				if (e.getKeyChar() == KeyEvent.VK_ENTER) // 按回车键执行相应操作;
				{
					search();
					p.fields[1].requestFocus();
					p.fields[1].selectAll();
				}
			}
		});
		p.fields[2].addKeyListener(new KeyAdapter() {
			public void keyPressed(KeyEvent e) {
				if (e.getKeyChar() == KeyEvent.VK_ENTER) // 按回车键执行相应操作;
				{
					search();
					p.fields[2].requestFocus();
					p.fields[2].selectAll();
				}
			}
		});
		
		if(jf!=null) {
			jf.add(p);
	
			jf.setVisible(true);
			jf.repaint();
			if(iNumber!=null) {
				p.fields[0].setText(iNumber);
				p.fields[0].setEnabled(false);
				search();
			}
		}else {
			jdd.add(p);
			jdd.setTitle("技能矩阵");
			jdd.setModal(true);
			jdd.setResizable(false);
			if(iNumber!=null) {
				p.fields[0].setText(iNumber);
				search();
			}
			jdd.setVisible(true);
		}
		
	}
	

	
	protected void showSkillList(String iNumber, String iName, String iClass) throws Exception {
		String strsql="select tp.trainingPositionIndex,tp.name as 岗位,"
				+ "vtv.LV as 等级,vtv.invalidTime as 有效期,DATEDIFF(day, GETDATE(), vtv.invalidTime) as 剩余天数 \r\n" + 
				"from [human].[skillList_mft] slm \r\n" + 
				"LEFT JOIN [human].[trainingPosition] tp ON tp.trainingPositionIndex=slm.trainingPositionIndex \r\n" + 
				"LEFT JOIN [human].[vTrainingValidity] vtv ON vtv.trainingPositionIndex=slm.trainingPositionIndex \r\n" + 
				"and vtv.number='"+iNumber+"' \r\n" + 
				"order by vtv.LV desc,vtv.invalidTime desc ";//hideCol(JTable, int)掉index
		JTable t=sql.select(strsql);
		JDialog jf=new JDialog();
		v_skillListViewer vslv=new v_skillListViewer();
		jf.setSize(vslv.getWidth()+20, vslv.getHeight()+50);
        jf.setLocationRelativeTo(null);
        jf.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		jf.add(vslv);
		jf.setLayout(null);
		jf.setTitle("个人技能列表");
		jf.setModal(true);
		vslv.fields[0].setText(iNumber);
		vslv.fields[1].setText(iName);
		vslv.fields[2].setText(iClass);
		vslv.fields[0].setEditable(false);
		vslv.fields[1].setEditable(false);
		vslv.fields[2].setEditable(false);
		vslv.setTable1(t);
		vslv.tab01.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent event) {
				super.mouseClicked(event);
				try {
					int iRow = vslv.tab01.getSelectedRow();
					if (iRow >= 0) {
						String psIndex=""+vslv.tab01.getValueAt(iRow, 0);
						String strsql="select trainingProjectIndex,projectName as 培训,trainingResult as 考试分数,internshipResult as 评价分数,\r\n" + 
								"permissionTime as 通过时间,DATEDIFF(day, GETDATE(), vts.invalidTime) as 剩余天数\r\n" + 
								"from [human].[vTrainingState] vts  \r\n" + 
								"where vts.number='"+iNumber+"' and vts.trainingPositionIndex="+psIndex;
						JTable t=sql.select(strsql);
						vslv.setTable2(t);
						
						
					}
				} catch (Exception e) {
					String str = errCodeManagement.getErrText(e.getMessage());
					mt.show(str);
				}
			}
		});
		freshTrainingList(vslv,iNumber);
		
		
		jf.setVisible(true);
	}
	
	

	private void freshTrainingList(v_skillListViewer vslv, String iNumber) throws Exception {
		String strsql="SELECT ts.tips as 备注,ts.positionID ,tpt.name as 岗位,ts.projectID,tpj.name as 培训,\r\n" + 
				"ts.trainingResult as 考试分数,ts.internshipResult as 评价分数,ts.createTime as 报名时间 \r\n" + 
				"FROM [human].[trainingState] ts \r\n" + 
				"LEFT JOIN [human].[trainingPosition] tpt ON tpt.trainingPositionIndex=ts.positionID\r\n" + 
				"LEFT JOIN [human].[trainingProject] tpj ON tpj.trainingProjectIndex=ts.projectID\r\n" + 
				"where ts.state>0 and ts.employeeID='"+iNumber+"' \r\n" + 
				"ORDER BY ts.createTime desc \r\n";
		JTable t=sql.select(strsql);
		vslv.setTable3(t);
	}

	public String getInputString(String MSG) {
		String result="";
		JDialog jd=new JDialog();
		v_getText iP=new v_getText();
		jd.setSize(iP.getWidth(),iP.getHeight()+20);
		jd.setLocationRelativeTo(null);
		jd.add(iP);
		iP.setMSG(MSG);
		iP.setLocation(0, 20);
		iP.buttonOK.addMouseListener(new MouseAdapter() { 
            public void mousePressed(MouseEvent e) {	
            	iP.buttonOK.setEnabled(false);
            	jd.setVisible(false);
            }  
    	});
		jd.setModal(true);
		jd.setVisible(true);
		if(!iP.buttonOK.isEnabled()) {
			result=iP.getText();
		}else {
			result=null;
		}
		jd.dispose();
		if(result!=null) {
			if(result.length()<1) {
				return null;
			}
		}
		return result;
	}
	
	public static String getTimeStamp(String iFormat){
    	//"2020-08-27 15:59:10";
    	String timestamp=new String();
    	if(iFormat==null||iFormat.length()<1) {
    		iFormat="yyyy-MM-dd HH:mm:ss SSS";
    	}
    	SimpleDateFormat t = new SimpleDateFormat(iFormat);
    	timestamp=""+t.format(new Date());
    	return timestamp;
    }


}
